package com.ling.common.library.view.image

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.ling.common.utils.R

/**
 * @author Ling
 * @date :2024/7/16 10:38
 */
class RoundImageView : AppCompatImageView {

    private var radius = floatArrayOf(0f , 0f , 0f , 0f , 0f , 0f , 0f , 0f)
    private var height = 0
    private var width = 0
    private val mPath by lazy { Path() }
    private val mRectF by lazy { RectF() }

    constructor(context: Context) : this(context , null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs ,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr){
        initView(attrs)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        height = getHeight()
        width = getWidth()
    }

    private fun initView(attrs: AttributeSet?){
        //读取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView)
        val allRadius = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_all_radius, 0).toFloat()
        if(allRadius == 0f){
            val lt = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_lt_radius, 0).toFloat()
            radius[0] = lt
            radius[1] = lt

            val rt = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_rt_radius, 0).toFloat()
            radius[2] = rt
            radius[3] = rt

            val rb = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_rb_radius, 0).toFloat()
            radius[4] = rb
            radius[5] = rb

            val lb = typedArray.getDimensionPixelOffset(R.styleable.RoundImageView_lb_radius, 0).toFloat()
            radius[6] = lb
            radius[7] = lb

        }else{
            for(index in radius.indices){
                radius[index] = allRadius
            }
        }

        typedArray.recycle()
    }



    override fun onDraw(canvas: Canvas) {
        if (width > 0 && height > 0) {
            mRectF.set(0f , 0f, width.toFloat() , height.toFloat())
            mPath.addRoundRect(mRectF, radius, Path.Direction.CW)
            canvas.clipPath(mPath)
        }
        super.onDraw(canvas)
    }
}